package com.nerve.cloudoffice.service.impl;

import java.util.Date;
import java.util.List;

import com.nerve.cloudoffice.common.SessionUtil;
import com.nerve.cloudoffice.domain.Message;
import com.nerve.cloudoffice.domain.dao.MessageDao;
import com.nerve.cloudoffice.domain.dao.UserDao;
import com.nerve.cloudoffice.service.IMService;
import com.nerve.cloudoffice.web.model.MessageModel;

public class IMServiceImpl implements IMService{
	
	private MessageDao dao;
	private UserDao userDao;
	
	private MessageDao getDao(){
		if(dao == null)
			dao = new MessageDao();
		
		return dao;
	}
	
	private UserDao getUserDao(){
		if(userDao == null)
			userDao = new UserDao();
		
		return userDao;
	}
	
	public void get(MessageModel model) throws Exception {
		StringBuilder hql = new StringBuilder("FROM Message as m where 1=1");
		
		int toId = 0;
		if(model.getToId() > 0){
			toId = model.getToId();
		}
		
		if(model.getId() == 0)
			model.setId(SessionUtil.getLoginUser().getId());
		
		int  id = model.getId();
		if(model.getAll() == 0){
			hql.append(" and m.read=0");
		}
			
		if(toId == 0){
			//只获取接收信息者为 id
			hql.append(" and m.toUser.id =" + id);
		}else{
			hql.append(
					String.format(" and ((m.fromUser.id=%1$d and m.toUser.id=%2$d) or (m.fromUser.id=%3$d and m.toUser.id=%4$d))", 
							id, toId, toId, id)
			);
		}
		
		System.out.println(hql.toString());
		
		List<Message> messageL = getDao().getList(
				hql.toString(), 
				1, 
				40
				);
		
		model.setMessageList(messageL);
		
		System.out.println("list size:" + messageL.size());
		for(Message m:messageL){
			m.setRead(true);
			getDao().merge(m);
		}
	}

	public void save(MessageModel model) throws Exception {
		if(model.getId() == 0){
			model.setId(SessionUtil.getLoginUser().getId());
		}
		
		if(model.getToId() <= 0)
			throw new RuntimeException("没有接收人！");
		
		if(model.getMessage() == null && model.getMessage().length() == 0)
			throw new RuntimeException("内容不能为空");
		
		Message msg = new Message();
		msg.setFromUser(getUserDao().getById(model.getId()));
		msg.setToUser(getUserDao().getById(model.getToId()));
		msg.setMessage(model.getMessage());
		msg.setJoinDate(new Date());
		msg.setRead(false);
		
		getDao().save(msg);
	}
}
